from __future__ import with_statement
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson as json

import logging

from Cyworld import Cyworld

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.redirect("/static/index.html")
        
class FoldersHandler(webapp.RequestHandler):
    def get(self):
        self._show(self.request.GET)
        
    def post(self):
        self._show(self.request.POST)
        
    def _show(self, param):
        cyworld = Cyworld(tid = param['tid'], email = param['email'] if param.has_key('email') else None, password = param['password'] if param.has_key('password') else None)
        result = json.dumps(cyworld.get_photo_folder_list() if self.type == 'photo' else cyworld.get_diary_folder_list())
        self.response.out.write('%s(%s)' % (param['callback'], result) if param.has_key('callback') else result)
        
class PhotoFoldersHandler(FoldersHandler):
    type = 'photo'
    
class DiaryFoldersHandler(FoldersHandler):
    type = 'diary'
        
class ExportHandler(webapp.RequestHandler):
    def get(self):
        self.error(500)
        
class LoginHandler(webapp.RequestHandler):
    def post(self):
        try:
            cyworld = Cyworld(tid = self.request.POST['tid'], email = self.request.POST['email'], password = self.request.POST['password'])
            result = json.dumps({'tid': cyworld.get_tid(), 'email': self.request.POST['email'], 'password': self.request.POST['password']})
            self.response.out.write('%s(%s)' % (self.request.POST['callback'], result) if self.request.POST.has_key('callback') else result)
        except Exception, e:
            logging.error(e)
            self.response.out.write('false')

class TidHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write(json.dumps({'tid': Cyworld(id = self.request.GET['id']).get_tid()}))
        
def main(): 
    run_wsgi_app(webapp.WSGIApplication([('/', MainHandler), ('/folders/photo', PhotoFoldersHandler), ('/folders/diary', DiaryFoldersHandler), ('/export', ExportHandler), ('/login', LoginHandler), ('/tid', TidHandler)], debug=True))

if __name__ == '__main__':
    main()